<?php

declare(strict_types=1);

namespace app\model;

use think\model\concern\SoftDelete;
use app\model\common\{
    BaseModel,
    HasPswdTrait,
    TokenTrait
};
use app\libs\token\driver\RedisToken;

/**
 * 管理员
 */
class Admin extends BaseModel
{
    public static $modelAlias = '管理员';

    protected $table = 'admin';
    protected $pk = 'id';

    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;

    use HasPswdTrait;

    // 使用Token
    use TokenTrait;
    protected static $traitTokenConfig = [
        'class' => RedisToken::class,
        'name' => 'Admin',  // token标识
        'expire_time' => 7200, // token有效时长，秒
    ];

    protected $json = [];
    protected $jsonAssoc = true;

    protected $hidden = ['delete_time', 'pswd', 'pswd_salt'];

    /** 写入后事件 */
    public static function onAfterWrite($model)
    {
        // 更新数据到Token中
        static::getTokenApp()->saveData($model['id'], $model);
    }

    /**
     * 储存登录信息
     */
    public function updateLoginInfo(): self
    {
        $this->save([
            'last_login_ip' => request()->ip(),
            'last_login_time' => date('Y-m-d H:i:s'),
        ]);
        return $this;
    }
}
